#' gsaanno_kegg UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd
#'
#' @importFrom shiny NS tagList
mod_gsaanno_kegg_ui <- function(id){
  ns <- NS(id)
  tagList(
    shinyWidgets::prettyRadioButtons(
      inputId = ns("species"),
      label = "Choices Species",
      choices = c("Human" = "hsa", "Mouse" = "mmu"),
      icon = icon("eye-dropper"),
      bigger = TRUE,
      inline = TRUE,
      fill = TRUE,
      plain = TRUE,
      status = "success",
      animation = "pulse"
    ),
    shinyWidgets::sliderTextInput(
      inputId = ns("pvalue"),
      label = "Choose a pvalue:",
      choices = seq(from = 0.05,
                    to = 0.01,
                    by = -0.01),
      grid = TRUE
    ),
    shinyWidgets::sliderTextInput(
      inputId = ns("qvalue"),
      label = "Choose a qvalue:",
      choices = seq(from = 0.05,
                    to = 0.01,
                    by = -0.01),
      grid = TRUE
    ),
    shinyWidgets::materialSwitch(
      inputId = ns("circle"),
      label = "Circle Style",
      value = TRUE,
      status = "primary"
    ),
    # shinycustomloader::withLoader(
    #   plotOutput(ns("keggnet")),
    #   type = "html",
    #   loader = "dnaspin"
    # )
    bs4Dash::bs4Card(
      title = "CnetPlot",
      width = NULL,
      maximizable = TRUE,
      boxToolSize = "xs",
      elevation = 3,
      headerBorder = FALSE,
      shinycustomloader::withLoader(
        echarts4r::echarts4rOutput(ns("netplot"),width = "100%",
                                   height = "800px"),
        type = "html",
        loader = "dnaspin"
      )
    ),
    shinycustomloader::withLoader(
      plotOutput(ns("keggdot")),
      type = "html",
      loader = "dnaspin"
    )
  )
}

#' gsaanno_kegg Server Functions
#'
#' @noRd
mod_gsaanno_kegg_server <- function(id,fileUpload=""){
  moduleServer( id, function(input, output, session){
    ns <- session$ns
    geneID <- reactive({
      fileUpload$geneID()
    })

    idType <- reactive({
      fileUpload$idType()
    })

    ENTREZID <- reactive({
      geneID <- geneID()
      geneID <- geneID[,1]
      idType <- idType()
      df <- clusterProfiler::bitr(unique(geneID), fromType = idType,
                                  toType = c( "ENTREZID" ),
                                  OrgDb = org.Hs.eg.db::org.Hs.eg.db)
      df$ENTREZID
    })

    kk <- reactive({
      # library(createKEGGdb)
      # species <-c("mmu","hsa")
      # create_kegg_db(species)
      # library(KEGG.db)
      # organism: https://www.genome.jp/kegg/catalog/org_list.html
      ENTREZID <- ENTREZID()
      enrichKK <- clusterProfiler::enrichKEGG(gene         =  ENTREZID,
                                              organism     = 'hsa',
                                              #universe     = gene_all,
                                              pvalueCutoff = input$pvalue,
                                              qvalueCutoff =input$qvalue,
                                              use_internal_data = T)
      DOSE::setReadable(enrichKK, OrgDb='org.Hs.eg.db',keyType='ENTREZID')
    })

    tmp <- reactive({
      enrichKK <- kk()
      # get data frame
      tmp=enrichKK@result
      # top 5
      head(tmp[ order(tmp$pvalue, decreasing = FALSE), ], round(5))
    })

    dataf <- reactive({
      tmp <- tmp()
      # get gene ID
      geneSets <- stats::setNames(strsplit(as.character(tmp$geneID), "/",
                                    fixed = TRUE), tmp$Description)
      list2df(geneSets)
    })

    nodes <- reactive({
      tmp <- tmp()
      dataf <- dataf()
      # kegg and rename cols
      nodes1 <- tmp[,c(2,5,9)]
        # dplyr::select(Description, pvalue, Count)
        # dplyr::rename(name = Description,value = pvalue,size = Count)
      colnames(nodes1) <- c("name", "value", "size")
      # add group
      nodes1$group <- nodes1$name

      # gene and add group
      nodes2 <- data.frame(
        name = dataf$Gene,
        value = 1,
        size = mean(tmp$Count)/2,
        group = "Genes"
      )

      # combine
      nodes <- rbind(nodes1,nodes2)
      row.names(nodes) <- NULL
      nodes$size <- as.integer(nodes$size)
      nodes$size <- as.numeric(nodes$size)*2
      nodes[!duplicated(nodes[,1]),]
    })

    edges <- reactive({
      dataf <- dataf()
      # dataf %>%
      #   dplyr::rename(source = categoryID, target = Gene)
      colnames(dataf) <- c("source", "target")
      dataf
    })

    output$keggdot <- renderPlot(
      clusterProfiler::dotplot(kk())
    )


    # output$keggnet <- renderPlot(
    #   clusterProfiler::cnetplot(kk(), categorySize="pvalue", colorEdge = TRUE)
    # )
    output$netplot <- echarts4r::renderEcharts4r({
      nodes <- nodes()
      edges <- edges()
      if (input$circle == TRUE) {
        echarts4r::e_charts(renderer = "svg") %>%
          echarts4r::e_graph(
            layout = "circular",
            name = TRUE,
            rm_x = TRUE,
            rm_y = TRUE,
            roam = TRUE,
            draggable = TRUE,
            nodeScaleRatio = 0.6,
            layoutAnimation = TRUE,
            circular = list( rotateLabel=TRUE),
            itemStyle = list(opacity = 0.8),
            lineStyle = list(color = 'source',curveness = 0.3),
            label = list(show = TRUE,
                         position= 'right',
                         formatter= '{b}')
          ) %>%
          echarts4r::e_graph_nodes(nodes, name, value, size, group) %>%
          echarts4r::e_graph_edges(edges, source, target) %>%
          #e_modularity() %>%
          echarts4r::e_tooltip() %>%
          echarts4r::e_toolbox_feature(feature = c("saveAsImage","dataZoom","dataView"))
      } else {
        echarts4r::e_charts(renderer = "svg") %>%
          echarts4r::e_graph(
            layout = "force",
            name = TRUE,
            rm_x = TRUE,
            rm_y = TRUE,
            roam = TRUE,
            draggable = TRUE,
            nodeScaleRatio = 0.6,
            layoutAnimation = TRUE,
            animationDuration=1500,
            edgeSymbol=c('', 'arrow'),
            edgeSymbolSize = 5,
            animationEasingUpdate='cubicOut',
            animationEasing = 'cubicOut',
            categories = 'webkitDep.categories',
            force = list(edgeLength=5, repulsion = 300, gravity = 0.6,
                         layoutAnimation = TRUE,edgeLength =250,initLayout=T),
            circular = list( rotateLabel=TRUE),
            #itemStyle = list(opacity = 0.8),
            lineStyle = list(color = 'source',curveness = 0.1,width=1),
            emphasis = list(focus="adjacency",lineStyle = list(width = 2)),

            label = list(show = TRUE,
                         position= 'right',
                         formatter= '{b}')
          ) %>%
          echarts4r::e_graph_nodes(nodes = nodes, names = name, value = value, size = size,category = group) %>%
          echarts4r::e_graph_edges(edges, source, target) %>%
          #e_modularity() %>%
          echarts4r::e_tooltip() %>%
          echarts4r::e_toolbox_feature(feature = c("saveAsImage","dataZoom","dataView")) %>%
          echarts4r::e_color(
            c('#fbb4ae','#b3cde3','#ccebc5','#decbe4','#fed9a6')
          )
      }
    })

  })
}

## To be copied in the UI
# mod_gsaanno_kegg_ui("gsaanno_kegg_ui_1")

## To be copied in the server
# mod_gsaanno_kegg_server("gsaanno_kegg_ui_1")
